package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.mapper.LoginMapper;
import com.itheima.pojo.Emp;
import com.itheima.pojo.EmpDot;
import com.itheima.pojo.LoginInfo;
import com.itheima.service.LoginService;
import com.itheima.utlis.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private LoginMapper loginMapper;

    @Override
    public LoginInfo getEmpByUsernameAndPwd(EmpDot e) {
        String username = e.getUsername();
        String password = e.getPassword();

        // 使用 MyBatis-Plus 的 LambdaQueryWrapper 查询
        Emp emp = loginMapper.selectOne(
                new LambdaQueryWrapper<Emp>()
                        .eq(Emp::getUsername, username)
                        .eq(Emp::getPassword, password)
        );

        if (emp == null) {
            throw new RuntimeException("用户名或密码错误");
        }

        LoginInfo loginInfo = new LoginInfo();
        loginInfo.setId(emp.getId());
        loginInfo.setUsername(emp.getUsername());
        loginInfo.setName(emp.getName());

        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", emp.getId());
        claims.put("name", emp.getName());
        String token = JwtUtils.generateJwt(claims);
        loginInfo.setToken(token);

        return loginInfo;
    }
}